package com.project.config;

import java.util.List;
import java.util.Map;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.mapdb.DB;
import org.mapdb.DBMaker;

import static dev.langchain4j.data.message.ChatMessageDeserializer.messagesFromJson;
import static dev.langchain4j.data.message.ChatMessageSerializer.messagesToJson;
import static org.mapdb.Serializer.STRING;


/**
 * @Author: zhoujinchuan
 * @Description: （持久化存储）
 * @Date: 2025/2/26 9:19
 */
public class PersistentChatMemoryStore implements ChatMemoryStore {

    /**
     * MapDB是一个嵌入式数据库，提供基于磁盘或内存的集合,这里用来存储聊天对话信息
     */
    private final DB db = DBMaker.fileDB("chat-memory.db").transactionEnable().make();
    private final Map<String, String> map = db.hashMap("messages", STRING, STRING).createOrOpen();


    @Override
    public List<ChatMessage> getMessages(Object memoryId) {
        String json = map.get(String.valueOf(memoryId));
        return messagesFromJson(json);
    }

    @Override
    public void updateMessages(Object memoryId, List<ChatMessage> messages) {
        String json = messagesToJson(messages);
        map.put(String.valueOf(memoryId), json);
        db.commit();
    }

    @Override
    public void deleteMessages(Object memoryId) {
        map.remove(String.valueOf(memoryId));
        db.commit();
    }
}
